# -*- coding: utf-8 -*-
# Create your views here.
from django.shortcuts import render_to_response
from dgmessages.models import Message,Guest,Settings
from dgmessages.forms import AddNewForm, SettingsForm
from django.template import RequestContext
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.template import RequestContext

from django.contrib import auth # authentification part
from django.core.urlresolvers import reverse # for reverse in HttpResponseRedirect

from datetime import datetime

def index_page(request):
    '''index page displays messages'''
    max_posts_page = Settings.objects.get(name="postsnumber").value_int
    if not max_posts_page:
        max_posts_page = 3 # default value        
    site_title = Settings.objects.get(name="sitetitle").value_char
    
    latest_messages_list = Message.objects.all().order_by('-date')
    paginator = Paginator(latest_messages_list, max_posts_page)

   # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        messages = paginator.page(page)
    except (EmptyPage, InvalidPage):
        messages = paginator.page(paginator.num_pages)

    # context_instance - need to pass MEDIA_URL in templates
    return render_to_response('index.html',
                    {'messages_list':messages, 'enableposting': check_enablepostings(),
                    'site_title': site_title}, 
                    context_instance = RequestContext(request))


def addpost_page(request):
    '''adds a new page but only if enableposting is set'''
    if not check_enablepostings():
        return HttpResponseRedirect("/")
    
    errors = []

    if request.POST:
        form = AddNewForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            guestob = Guest(name = cd['name'],
                            URL = cd['URL'],
                            email = cd['email'])
            guestob.save()

            messageob = Message(guest = guestob,
                              message = cd['message'])
            messageob.save()
            return HttpResponseRedirect('/')
    else:
        form = AddNewForm()

    return render_to_response('add.html', {'form': form}, context_instance=RequestContext(request))


def admin_index_page(request):
    '''main page for administration'''
    max_posts_page = Settings.objects.get(name="postsnumber").value_int
    if not max_posts_page:
        max_posts_page = 3 # default value        
    site_title = Settings.objects.get(name="sitetitle").value_char
    
    latest_messages_list = Message.objects.all().order_by('-date')
    paginator = Paginator(latest_messages_list, max_posts_page)

   # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        messages = paginator.page(page)
    except (EmptyPage, InvalidPage):
        messages = paginator.page(paginator.num_pages)

    # context_instance - need to pass MEDIA_URL in templates
    return render_to_response('admin/index.html',
            {'messages_list':messages, 'subtitle': 'List - main page'},
            context_instance = RequestContext(request))


def admin_logout_page(request):
    '''logout function for admin'''
    auth.logout(request)
    return HttpResponseRedirect("/")


def admin_settings_page(request):
    '''settings page for admin'''
    errors = []

    # ------------------------------------------------
    # SETTINGS
    setob_ep, created = Settings.objects.get_or_create(name="enableposting")
    setob_np, created = Settings.objects.get_or_create(name="postsnumber")
    setob_st, created = Settings.objects.get_or_create(name="sitetitle")

    if request.POST:
        form = SettingsForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            setob_ep.value_bool = cd['enable_postings']
            setob_np.value_int = cd['posts_number']
            setob_st.value_char = cd['site_title']
            setob_ep.save()
            setob_np.save()
            setob_st.save()
            return HttpResponseRedirect(reverse('admin_settings'))
    else:
        # load it with saved settings
        form = SettingsForm(initial= {
                'enable_postings' : setob_ep.value_bool,
                'posts_number' : setob_np.value_int,
                'site_title' : setob_st.value_char })

    return render_to_response('admin/settings.html',
            {'subtitle': 'Settings - for the guestbook', 'form': form},
            context_instance = RequestContext(request))


def admin_delete_post(request,mid):
    '''deletes a post'''
    Message.objects.get(id=mid).delete()
    return HttpResponseRedirect(reverse('admin_list'))


def requires_login(view):
    def new_view(request, *args, **kwargs):
        print request
        if not request.user.is_authenticated():
            return HttpResponseRedirect('/admin/login/')
        return view(request, *args, **kwargs)
    return new_view


def check_enablepostings():
    '''check if enableposting is enabled'''
    return Settings.objects.get(name="enableposting").value_bool

